package treqs.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import java.util.List;

import treqs.model.*;

/**
 * Servlet implementation class listReqsServlet
 */
public class listReqsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public listReqsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// Start EntityManagerFactory
		EntityManagerFactory emf = 
			Persistence.createEntityManagerFactory("treqs");
		// First unit of work
		EntityManager em = emf.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		Reqs requirement = new Reqs("Hello World1");
		em.persist(requirement);
		Reqs requirement2 = new Reqs("Hello World2");
		em.persist(requirement2);
		tx.commit();
		em.close();

		// Second unit of work
		EntityManager newEm = emf.createEntityManager();
		EntityTransaction newTx = newEm.getTransaction();
		newTx.begin();
		List requirements = newEm.createQuery(
				"select r from Reqs r order by r.name asc")
							.getResultList();
		System.out.println( requirements.size() + " requirement(s) found" );
		for (Object r : requirements) {
			Reqs loadedRequirement = (Reqs) r;
			System.out.println(loadedRequirement.getName());
		}
		newTx.commit();
		newEm.close();

		// Shutting down the application
		emf.close();

	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
